/* eslint-disable comma-dangle */
import React, { useState, useEffect } from 'react';
import s from './style.module.less';
import BreadCrumbBox from '@/components/BreadCrumb';
import { getMailList, setMailStatus, delMails, setAllMails, delAllMails} from '~/API/index';
import { Button, Message, Checkbox, Confirm, Pagination, Loading } from '@knownsec/react-component';
import cn from 'classnames';
import EmptyData from '@/components/EmptyData';
import moment from 'moment';
import { deepClone } from '@/utils'

function messageList() {
  const [loading, setLoading] = useState(false);
  const [selectIds, setSelect] = useState([]);
  const [datalist, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  
  const arr = [{ link: '', name: '消息', active: true }];
  
  const signRead = (idArr) => {
    let text = '确认要将选中的消息标为已读吗？'
    if(idArr==='all'){
      text = '确认要将全部消息标为已读吗？'
    }
    Confirm({
      title: '确认提示',
      pro: true,
      message: <div className="confirmbox">{text}</div>,
      onconfirm: async () => {
        setLoading(true)
        let res={}
        if(idArr==='all'){
          res = await setAllMails({status: 1})
        }else{
          res = await setMailStatus({status: 1, inbox_mail_ids: idArr})
        }
        setLoading(false)
        if(res.status === 'success'){
          Message.show({
            pro: true,
            type: 'success',
            message: '已读成功',
            showClose: false,
          });
          setSelect([])
          getData('empty')
        }else{
          Message.show({
              pro: true,
              type: 'error',
              message: res.data?.detail,
              showClose: false,
            });
        }
      },
      oncancel: () => {},
    });
    
  };
  const delMsg = (type) => {
    let text = '确认要删除选中的消息吗？'
    if(type==='all'){
      text = '确认要删除全部的消息吗？'
    }
    Confirm({
      pro: true,
      title: '确认提示',
      message: <div className="confirmbox">{text}</div>,
      onconfirm: async () => {
        setLoading(true)
        let res = {}
        if(type==='all'){
          res = await delAllMails()
        }else{
          res = await delMails({ inbox_mail_ids: selectIds })
        }
        setLoading(false)
        if (res.status == 'success') {
          setSelect([])
          getData();
          Message.show({
            pro: true,
            type: 'success',
            message: '删除消息成功',
            showClose: false,
          });
        }else{
          Message.show({
              pro: true,
              type: 'error',
              message: res.data?.detail,
              showClose: false,
            });
        }
      },
      oncancel: () => {},
    });
  };
  function selectAll() {
    let sids = deepClone(selectIds);
    const d = datalist.map(i => {
      i.checked = true
      if(sids.indexOf(i.inbox_mail_id) === -1){
        sids.push(i.inbox_mail_id);
      }
      return i
    });
    setData(d)
    setSelect(sids)
  }
  function cancelSelect() {
    const d = datalist.map(i => {
      i.checked = false
      return i
    });
    setData(d)
    setSelect([])
  }
  function onchange(e, _index) {
    datalist[_index].checked = e.value
    const item = [].concat(datalist)
    let sids = deepClone(selectIds)
    if(e.value){
      sids.push(datalist[_index].inbox_mail_id)
    }else{
      const n = sids.indexOf(datalist[_index].inbox_mail_id)
      if(n>-1){
        sids.splice(n,1)
      }
    }
    setData(item);
    setSelect(sids)
  }
  function getData(type,p,l) {
    setLoading(true)
    getMailList({page: p?p:page, limit: l?l:pageSize}).then((res) => {
      setLoading(false)
      if (res.status === 'success') {
        const d = res.data?.data || []
        d.map(i=> {
          if(selectIds.indexOf(i.inbox_mail_id)>-1 && type !== 'empty'){
            i.checked = true
          }else{
            i.checked = false
          }
          return i
        })
        setData(d);
        setTotal(res.data.total)
      }
    });
  }
  function onSearchChange(page, size) {
    setPageSize(size)
    setPage(page)
    getData(1,page, size)
  }
  useEffect(() => {
    getData();
  }, []);
  return (
    <>
      <BreadCrumbBox arr={arr}></BreadCrumbBox>
      <Loading show={loading}></Loading>
      <div className={s.msgcontent}>
        <div className={s.topline}>
          <Button
            disabled={!selectIds.length}
            onClick={()=>delMsg()}
            className={cn(s.mr8, 'delete-btn')}
            pro
            type="default"
          >
            删除
          </Button>
          <Button disabled={!selectIds.length} className={cn(s.mr8)} pro type="default" onClick={()=>signRead(selectIds)}>
            标为已读
          </Button>
          <Button disabled={total<1} className={cn(s.mr8)} pro type="default" onClick={()=>signRead('all')}>
            全部已读
          </Button>
          <Button disabled={total<1} className={cn(s.mr8)} pro type="default" onClick={()=>delMsg('all')}>
            全部删除
          </Button>
        </div>
        <div className={s.totalline}>
          {datalist.filter(i => i.checked).length === datalist.length ? (<span onClick={() => cancelSelect()}>取消选中</span>) : (<span onClick={() => selectAll()}>全选</span>)} <span>选中{selectIds.length}条</span>
        </div>
        <div className={s.msglist}>
          <div className={s.listbox}>
            {datalist.length>0 ? (
              datalist.map((item, index) => (
                  <>
                    <div className={cn(s.messageItem, item.status ? s.readed : '')}>
                      <div className={s.wcheckbox}>
                        <Checkbox
                          checked={item.checked}
                          onChange={(e) => {
                            onchange(e, index);
                          }}
                        />
                      </div>
                      <div className={s.messtitle}>
                        {/* TODO: 跳转
                           <a href={`/#/dashboard/?id=${item.title}`} target="_blank" rel="noreferrer">
                          {item.title} 
                        </a>
                        */}
                     
                        {item.title} 
                        <span>{item.created_at?moment(item.created_at).format('YYYY-MM-DD HH:mm:ss'):'-'}</span>
                      </div>
                      <p>{item.content}</p>
                      {item.status ? (
                        <span className={s.hasread}>已读</span>
                      ) : (
                        <span
                          onClick={() => signRead([item.inbox_mail_id])}
                          style={{ color: '#0b6fd6' }}
                          className={s.needread}
                        >
                          标为已读
                        </span>
                      )}
                    </div>
                  </>
                )
              )
            ) : (
              <EmptyData />
            )}
            {total > 10 && (<Pagination
              key={Number(123)}
              className={s.pagination}
              current={page}
              showQuickJumper={{ goButton: true }}
              showSizeChanger={true}
              pageSize={pageSize}
              pageSizeOptions={['10', '20', '50']}
              total={total}
              showTotal={(total) => `共${total}条`}
              onChange={(page, size) => {
                onSearchChange(page, size);
              }}
            />)}
          </div>
        </div>
      </div>
    </>
  );
}

export default messageList;
